package no.uib.hplims.views.auth;

import no.uib.hplims.tools.SecurityUtil;
import no.uib.hplims.views.MenuTabSheet;

import org.vaadin.appfoundation.authentication.exceptions.AccountLockedException;
import org.vaadin.appfoundation.authentication.exceptions.InvalidCredentialsException;
import org.vaadin.appfoundation.view.AbstractView;
import org.vaadin.appfoundation.view.ViewHandler;

import com.vaadin.event.ShortcutAction.KeyCode;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Layout;
import com.vaadin.ui.PasswordField;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;

public class LoginScreen extends AbstractView<VerticalLayout> {

	private static final long serialVersionUID = -3820919439465943781L;

	public LoginScreen() {
		super(new VerticalLayout());
		getContent().addComponent(buildLoginForm());
	}

	public void activated(Object... params) {
		// TODO Auto-generated method stub

	}

	public void deactivated(Object... params) {
		// TODO Auto-generated method stub

	}

	private Layout buildLoginForm() {
		FormLayout layout = new FormLayout();
		// Create a label which we can use to give feedback to the user
		final Label feedbackLabel = new Label();

		// Create input fields for username and password
		final TextField usernameField = new TextField("Username");
		usernameField.setInputPrompt("Username");
		final PasswordField passwordField = new PasswordField("Password");
		passwordField.setInputPrompt("Password");

		// Add the login button
		Button loginButton = new Button("Login", new ClickListener() {

			private static final long serialVersionUID = -5577423546946890721L;

			public void buttonClick(ClickEvent event) {
				// Try to log in the user when the button is clicked
				String username = (String) usernameField.getValue();
				String password = (String) passwordField.getValue();
				try {
					SecurityUtil.authenticateUser(username, password);
					// User is now logged in, now change the view or do
					// whatever is needed after a login.
					ViewHandler.activateView(MenuTabSheet.class);
					usernameField.setValue("");
					passwordField.setValue("");
					feedbackLabel.setValue("");
				} catch (InvalidCredentialsException e) {
					feedbackLabel
							.setValue("Either username or password was wrong");
				} catch (AccountLockedException e) {
					feedbackLabel.setValue("The given account has been locked");
				}
			}
		});
		loginButton.setClickShortcut(KeyCode.ENTER);

		layout.addComponent(feedbackLabel);
		layout.addComponent(usernameField);
		layout.addComponent(passwordField);
		layout.addComponent(loginButton);

		return layout;
	}

}
